import CloseOutlined from "@ant-design/icons/lib/icons/CloseOutlined";
import React, { useState } from "react";
import { addEnv } from "../../service";
import { Environment } from "../../types";
import { notification } from "antd";
 
 

interface EnvAddProps {
  visible: boolean;
  onClose: () => void;
  onFlush: (flush:boolean)=>void;
}

const EnvAdd: React.FC<EnvAddProps> = ({ visible, onClose, onFlush }) => {
  const defaultEnvironments: { description: string; name: string }[] = [
    { description: "开发", name: "dev" },
    { description: "测试", name: "qa" },
    { description: "灰度", name: "pre" },
    { description: "正式", name: "prod" }
  ]; 
  const [selectedOptions, setSelectedOptions] = useState<string[]>(defaultEnvironments.map(env => env.name));
  const [environments, setEnvironments] = useState<Environment[]>([]);

  const handleOptionChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const value = event.target.value;
    const isChecked = event.target.checked;

    if (isChecked) {
      setSelectedOptions([...selectedOptions, value]);
    } else {
      setSelectedOptions(selectedOptions.filter(option => option !== value));
    }
  };

  const handleEnvironmentChange = (
    index: number,
    field: keyof Environment,
    value: string
  ) => {
    const newEnvironments = [...environments];
    newEnvironments[index][field] = value;
    setEnvironments(newEnvironments);
  };

  const handleAddEnvironment = () => {
    setEnvironments([...environments, { description: "", name: "" }]);
  };

  const handleRemoveEnvironment = (index: number) => {
    setEnvironments(environments.filter((_, envIndex) => envIndex !== index));
  };

  const handleSave = async() => {
    const allEnvironments:Array<any> = [
      ...defaultEnvironments.filter(env => selectedOptions.includes(env.name)),
      ...environments
    ];
    console.log("Selected Environments:", allEnvironments);
    try {
      await addEnv(allEnvironments)
      notification.success({message:"保存成功！"})      
      onFlush(true)
    } catch (error) {
      notification.error({message:"保存失败！"+error.message})      
    }
  };

  const handleClose = () => {
    onClose();
  };

  return (
    <div className={`fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50 ${visible ? '' : 'hidden'}`}>
      <div className="bg-white p-6 rounded-lg shadow-lg w-full md:w-1/3 mx-auto relative">
        {/* 关闭按钮 */}
        <button
          onClick={handleClose}
          className="absolute top-2 right-2 bg-gray-200 text-gray-600 p-2 rounded hover:bg-gray-300"
        >
          <CloseOutlined />
        </button>

        <h2 className="text-2xl font-bold mb-6">环境配置</h2>

        {/* 默认环境类型 */}
        <div className="mb-6">
          <label className="block text-gray-700 font-bold mb-2">勾选开启</label>
          <div className="flex justify-center  gap-4">
            {defaultEnvironments.map(env => (
              <label key={env.name} className="flex items-center">
                <input
                  type="checkbox"
                  value={env.name}
                  checked={selectedOptions.includes(env.name)}
                  onChange={handleOptionChange}
                  className="mr-2"
                />
                {env.description} ({env.name})
              </label>
            ))}
          </div>
        </div>

        {/* 动态添加的环境名称输入框 */}
        <div className="mb-6">
          {environments.map((env, index) => (
            <div key={index} className="flex gap-4 items-end">
              <div className="flex-1">
                <label className="block text-gray-700 font-bold mb-1">中文名称 (desc)</label>
                <input
                  type="text"
                  value={env.description}
                  onChange={(e) => handleEnvironmentChange(index, "description", e.target.value)}
                  className="border p-2 w-full rounded"
                />
              </div>
              <div className="flex-1">
                <label className="block text-gray-700 font-bold mb-1">英文名称 (name)</label>
                <input
                  type="text"
                  value={env.name}
                  onChange={(e) => handleEnvironmentChange(index, "name", e.target.value)}
                  className="border p-2 w-full rounded"
                />
              </div>
              <button
                onClick={() => handleRemoveEnvironment(index)}
                className="bg-red-500 text-white px-2 py-1 hover:bg-red-600 rounded"
              >
                删除
              </button>
            </div>
          ))}
        </div>

        {/* 按钮组：新增环境和保存 */}
        <div className="flex justify-center gap-4">
          <button
            onClick={handleAddEnvironment}
            className="bg-blue-500 text-white px-4 py-2 hover:bg-blue-600 rounded"
          >
            新增环境
          </button>
          <button
            onClick={handleSave}
            className="bg-green-500 text-white px-4 py-2 hover:bg-green-600 rounded"
          >
            保存
          </button>
        </div>
      </div>
    </div>
  );
};

export default EnvAdd;